package com.lswms.modules.lswms.controller.recipient;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lswms.modules.lswms.entity.recipient.RecipientReportEntity;
import com.lswms.modules.lswms.excel.recipient.RecipientsReportExcel;
import com.lswms.modules.lswms.service.statistics.StatisticsService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.druid.util.StringUtils;
import com.lswms.common.annotation.LogOperation;
import com.lswms.common.constant.Constant;
import com.lswms.common.page.PageData;
import com.lswms.common.utils.ExcelUtils;
import com.lswms.common.utils.IpUtils;
import com.lswms.common.utils.Result;
import com.lswms.common.validator.AssertUtils;
import com.lswms.common.validator.ValidatorUtils;
import com.lswms.common.validator.group.AddGroup;
import com.lswms.common.validator.group.DefaultGroup;
import com.lswms.common.validator.group.UpdateGroup;
import com.lswms.modules.lswms.MEGConstant;
import com.lswms.modules.lswms.dto.orders.OrderdetailDTO;
import com.lswms.modules.lswms.dto.recipient.RecipientsDTO;
import com.lswms.modules.lswms.entity.orders.OrderdetailEntity;
import com.lswms.modules.lswms.entity.orders.OrderdetaillistEntity;
import com.lswms.modules.lswms.entity.recipient.RecipientsEntity;
import com.lswms.modules.lswms.excel.recipient.RecipientsExcel;
import com.lswms.modules.lswms.service.recipient.RecipientsService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * ${comments}
 *
 * @author DX
 * @since 1.0.0 2021-07-19
 */
@RestController
@RequestMapping("lswms/recipients")
@Api(tags = "${comments}")
public class RecipientsController {
	@Autowired
	private RecipientsService recipientsService;

	@Autowired
	private StatisticsService statisticsService;

	@GetMapping("page")
	@ApiOperation("分页")
	@ApiImplicitParams({
			@ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
			@ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
			@ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String") })
//	@RequiresPermissions("lswms:recipients:page")
	public Result<PageData<RecipientsEntity>> page(@ApiIgnore HttpServletRequest request) {
		try {
			PageData<RecipientsEntity> page = recipientsService.pageBySql(request);

			return new Result<PageData<RecipientsEntity>>().ok(page);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().error(MEGConstant.IS_ERROR);
		}

	}

	@GetMapping("{id}")
	@ApiOperation("信息")
//	@RequiresPermissions("lswms:recipients:info")
	public Result<RecipientsDTO> get(@PathVariable("id") Long id) {
		RecipientsDTO data = recipientsService.get(id);

		return new Result<RecipientsDTO>().ok(data);
	}

	@PostMapping
	@ApiOperation("保存")
	@LogOperation("保存")
	@RequiresPermissions("lswms:recipients:save")
	public Result save(@RequestBody RecipientsDTO dto) {

		try {
			// 效验数据
			ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

			String msg = recipientsService.save1(dto);

			if (StringUtils.isEmpty(msg)) {
				return new Result();
			} else {
				return new Result().error(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().error(MEGConstant.IS_ERROR);
		}
	}

	@PutMapping
	@ApiOperation("修改")
	@LogOperation("修改")
	@RequiresPermissions("lswms:recipients:update")
	public Result update(@RequestBody RecipientsDTO dto) {
		try {
			// 效验数据
			ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

			String msg = recipientsService.valideAndUpdate(dto);
			if (StringUtils.isEmpty(msg)) {
				return new Result();
			} else {
				return new Result().error(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().error(MEGConstant.IS_ERROR);
		}
	}

	@DeleteMapping
	@ApiOperation("删除")
	@LogOperation("删除")
	@RequiresPermissions("lswms:recipients:delete")
	public Result delete(@RequestBody Long[] ids) {
		try {
			// 效验数据
			AssertUtils.isArrayEmpty(ids, "id");

			String msg = recipientsService.valideAnddelete(ids);

			if (StringUtils.isEmpty(msg)) {
				return new Result();
			} else {
				return new Result().error(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().error(MEGConstant.IS_ERROR);
		}

	}

	@GetMapping("export")
	@ApiOperation("导出")
	@LogOperation("导出")
	@RequiresPermissions("lswms:recipients:export")
	public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response)
			throws Exception {
		List<RecipientsEntity> list = recipientsService.listBySql(params);

		ExcelUtils.exportExcelToTarget(response, null, list, RecipientsExcel.class);
	}


	@GetMapping("export2")
	@ApiOperation("导出")
	@LogOperation("导出")
	//@RequiresPermissions("lswms:recipients:export2")
	public void export2(@ApiIgnore @RequestParam Map<String, Object> map, HttpServletResponse response)
			throws Exception {
		List<Map<String,Object>> list = statisticsService.getRecipientReport2(map);
//		System.out.println(list);
		List<RecipientReportEntity> list2  = new ArrayList<>();
		RecipientReportEntity recipientReportEntity = new RecipientReportEntity();
		for (Map<String,Object>  map2 :list){
			recipientReportEntity.setBackqty((BigDecimal) map2.get("backqty"));
			recipientReportEntity.setCardid((String) map2.get("cardid"));
			recipientReportEntity.setDamegeqty((BigDecimal)map2.get("damegeqty"));
			recipientReportEntity.setDescr((String)map2.get("descr"));
			recipientReportEntity.setFactorycdoe((String)map2.get("factorycdoe"));
			recipientReportEntity.setLot9((String)map2.get("lot9"));
			recipientReportEntity.setPrice((BigDecimal)map2.get("price"));
			recipientReportEntity.setQty((BigDecimal)map2.get("qty"));
			recipientReportEntity.setRecipient((String)map2.get("recipient"));
			recipientReportEntity.setRecipientid((String)map2.get("recipientid"));
			recipientReportEntity.setRecipienttime((String) map2.get("recipienttime"));
			recipientReportEntity.setRecipienttype((String)map2.get("recipienttype"));
			recipientReportEntity.setSku((String)map2.get("sku"));
			list2.add(recipientReportEntity);
		}
//		Integer a = (Integer) map.getOrDefault("cardId",0);
		ExcelUtils.exportExcelToTarget(response, null, list2, RecipientsReportExcel.class);
	}

	@PutMapping("release")
	@ApiOperation("发放")
	@RequiresPermissions("lswms:recipients:release")
	public Result<RecipientsDTO> release(@RequestBody List<RecipientsEntity> list) {

		try {
			HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
					.getRequest();
			String remoteAddr = IpUtils.getIpAddr(req);

			List<RecipientsEntity> orderList = list;
			String msg = recipientsService.release(orderList, remoteAddr);

			if (StringUtils.isEmpty(msg)) {
				return new Result();
			} else {
				return new Result().error(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().error(MEGConstant.IS_ERROR);
		}
	}

	@GetMapping("picklist/{tray}")
	@ApiOperation("信息")
	public Result picklist(@PathVariable("tray") String tray) {
		List<RecipientsEntity> data = recipientsService.getByTray(tray);

		return new Result().ok(data);
	}

	@PostMapping("savePicklist")
	@ApiOperation("拣选")
	public Result savePicklist(@RequestBody List<RecipientsEntity> list) {

		try {

			String msg = recipientsService.savePicklist(list);
			if (StringUtils.isEmpty(msg)) {
				return new Result();
			} else {
				return new Result().error(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().error(MEGConstant.IS_ERROR);
		}
	}

	@PostMapping("backToStereo")
	@ApiOperation("回库")
	public Result backToStereo(@RequestBody Map<String, Object> map) {

		try {

			String msg = recipientsService.backToStereo((String) map.get("tray"));
			if (StringUtils.isEmpty(msg)) {
				return new Result();
			} else {
				return new Result().error(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().error(MEGConstant.IS_ERROR);
		}
	}

	@PutMapping("delivery")
	@ApiOperation("发货")
	@RequiresPermissions("lswms:recipients:delivery")
	public Result<RecipientsEntity> delivery(@RequestBody List<RecipientsEntity> list) {

		try {
			String msg = recipientsService.delivery(list);

			if (StringUtils.isEmpty(msg)) {
				return new Result();
			} else {
				return new Result().error(msg);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result().error(MEGConstant.IS_ERROR);
		}
	}
}